package com.lwc.cfdns.utils;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 树结构处理
 *
 * @author luwc
 * @title TreeUtils
 * @description
 * @time 2023/5/8 16:39:06
 * @version: 1.0
 */
public class TreeUtils {

    /**
     * 递归转成树
     *
     * @param nodes
     * @param pid
     * @return List<T>
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/5/8 17:45:12
     */
    public static <T extends TreeNode> List<T> itemsMerge(List<T> nodes, Integer pid) {
        List<T> tree = new ArrayList<>();
        for (T node : nodes) {
            if (node.getPId().equals(pid)) {
                tree.add(findChildren(nodes, node));
            }
        }
        return null;
    }

    /**
     * 转成树型
     *
     * @param nodes
     * @return List<T>
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/5/8 22:11:11
     */
    public static <T extends TreeNode> List<T> itemsMerge(List<T> nodes) {
        List<T> tree = new ArrayList<>();
        for (T node : nodes) {
            if (node.getPId().equals(0)) {
                tree.add(findChildren(nodes, node));
            }
        }
        return null;
    }

    private static <T extends TreeNode> T findChildren(List<T> lists, T parentNode) {
        for (T node : lists) {
            if (parentNode.getId().equals(parentNode.getPId())) {
                parentNode.getChildren().add(findChildren(lists, node));
            }
        }
        return parentNode;
    }
}

@Data
abstract class TreeNode {
    private Integer id;
    private String title;
    private Integer pId;
    private List<TreeNode> children = new ArrayList<>();
}
